package com.mes.eventhandler;

import com.mes.data.EmesSize;
import com.mes.data.EmesXuantouModel;
import com.mes.data.EmesXuantouSize;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.*;
import org.openbravo.dal.service.OBDal;
import javax.enterprise.event.Observes;
import java.util.List;

public class XuantouModelEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EmesXuantouModel.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}

	public void onUpdate(@Observes EntityUpdateEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		changeDataSetName(event);
	}

	//新建头信息时同时保存BomItem
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		changeDataSetName(event);
	}

	private void changeDataSetName(EntityPersistenceEvent event) {
		final EmesXuantouModel xuantouModel = (EmesXuantouModel) event.getTargetInstance();
		setSizeMete(xuantouModel);
	}

	public void onDelete(@Observes EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}

	/**
	 * 根据标准用量设置其他尺码用量
	 */
	private void setSizeMete(EmesXuantouModel xuantouModel) {
		if (xuantouModel.getEmesXuantouSizeList().isEmpty()) {
			List<EmesSize> list = OBDal.getInstance().createQuery(EmesSize.class, "where active = true order by code asc").list();
			EmesXuantouSize xuanSize = null;
			for (EmesSize size : list) {
				xuanSize = new EmesXuantouSize();
				xuanSize.setEmesSize(size);
				xuanSize.setEmesXuantouModel(xuantouModel);
				xuantouModel.getEmesXuantouSizeList().add(xuanSize);
			}
		}
	}
}
